﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Web;

namespace PowerWaveAddin
{
    public class SimplePostHelper
    {
        private readonly string url;

        private WebClient webClient;

        public string Url
        {
            get { return url; }
        }


        public SimplePostHelper(string url)
        {
            this.url = url;

            if (this.url == null)
                throw new ArgumentNullException("url");

            this.webClient = new WebClient();
        }

        public string ExecutePost(IList<KeyValuePair<string, string>> data)
        {
            string postData = ConstructPostData(data);

            webClient.Headers.Add("content-type", "application/x-www-form-urlencoded");
            return this.webClient.UploadString(this.url, postData);
        }

        public string ExecuteGet(string url, NameValueCollection data)
        {
            webClient.QueryString = data;
            string response = webClient.DownloadString(url);
            return response;
        }

        private string ConstructPostData(IList<KeyValuePair<string, string>> data)
        {
            StringBuilder postData = new StringBuilder();

            foreach (KeyValuePair<string, string> item in data)
            {
                if (postData.Length > 0)
                    postData.Append("&");

                postData.Append(item.Key);
                postData.Append("=");
                postData.Append(item.Value);
            }

            return postData.ToString();
        }
    }
}
